<?php

namespace App\Models\Notice;

use App\Models\BaseModel;

class NoticeTemplate extends BaseModel
{

    protected $table = 'notice_templates';
    protected $fillable = ['title', 'content', 'description', 'template_id', 'type', 'data_scope'];
    public $params = ['title', 'content', 'description', 'template_id'];
    public $sorters = ['title', 'description', 'type'];

    public function addTemplate($data)
    {
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    public function deleteTemplate($id)
    {
        $noticeTemplate = $this->find($id);
        if ($noticeTemplate) {
            return $noticeTemplate->delete();
        } else {
            return null;
        }
    }

    public function editTemplate($id, $data)
    {
        $template = $this->find($id);
        if ($template) {
            return $template->update($data);
        } else {
            return null;
        }
    }

    public function getTemplateList($limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        $noticeTemplate = $this->orderBy($sorter[0], $sorter[1]);
        $noticeTemplate->select(['id', 'title', 'content', 'description', 'type', 'template_id']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'title':
                    $noticeTemplate->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }
        return $noticeTemplate->paginate($perPage)->toArray();
    }

    public function getTemplateListAll()
    {
        return $this->all(['id', 'title'])->toArray();
    }

    //查找模板获取模板内容
    public function getTemplate($id)
    {
        $template = $this->find($id);
        if ($template) {
            return $template;
        } else {
            return null;
        }
    }

}
